import 'dart:math';

import 'package:acgn_pioneer/models/_index.dart';

import '../public.dart';
import 'base_model.dart';

/// 漫画信息
class ComicModel extends BaseModel {
  int id; // 数字id
  String name; // 漫画名称
  String desc; // 漫画描述
  String authorName; // 作者
  int lastChapterId; // 最后一章id
  String lastChapterName; // 最后一章name
  String coverImg; // 封面图2x1
  String coverImg43; // 封面图4x3
  String copyrightType; // 版权类型
  int updateTime; // 最新更新时间
  List<String> tagList; // 标签列表
  List<ChapterModel> chapters; // 漫画章节信息
  bool isNoCopyright; // 是否有版权
  String sortTypeStr;
  int totalCollect; // 收藏|追更
  int shareCount; // 分享数
  String tagStr; // 标签数据

  ComicModel({this.id, this.isNoCopyright});

  ComicModel.fromJson(Map<String, dynamic> data) : super.fromJson(data) {
    id = data['comic_id'];
    name = data['comic_name'];
    desc = data['comic_desc'];
    authorName = data['author_name'];
    lastChapterName = data['lastchapter_title'];
    copyrightType = data['copyright_type_str'];
    updateTime = data['update_time'];
    coverImg = data['cover_img'];
    coverImg43 = data['cover_img_43'];
    chapters = installChapters(data['chapters'] ?? []);
    isNoCopyright = chapters.length == 0;
    if (chapters.length > 0) {
      lastChapterId = chapters[chapters.length - 1].id;
    }
    totalCollect = data['total_collect'];
    shareCount = data['share_count'];

    List<dynamic> sortTypes = data['sort_typelist'] ?? [];
    sortTypeStr = sortTypes
        .sublist(0, min(sortTypes.length, 2))
        .map((e) => e.values.first)
        .join('·');
  }

  List<ChapterModel> installChapters(dynamic data) {
    List<ChapterModel> chapters = [];
    data.forEach((item) {
      /// 为0状态章节不加载
      if (item['chapter_status'] == 0) {
        return;
      }
      var chapter = ChapterModel.fromJson(item);
      chapter.comicModel = this;
      chapters.add(chapter);
    });

    return chapters;
  }

  @override
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'desc': desc,
      'authorName': authorName,
      'lastChapterId': lastChapterId,
      'lastChapterName': lastChapterName,
      'copyrightType': copyrightType,
      'updateTime': updateTime,
      'tagList': tagList,
      'chapters': chapters,
      'totalCollect': totalCollect
    };
  }
}
